package com.yq.chaos.base.ui.act;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.jakewharton.rxbinding.view.RxView;
import com.trello.rxlifecycle.ActivityEvent;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.yq.chaos.base.event.BusFactory;
import com.yq.chaos.base.ui.help.UiCallback;
import com.yq.chaos.base.ui.help.UiDelegate;
import com.yq.chaos.base.ui.help.UiDelegateBase;

import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import me.yokeyword.fragmentation.SupportActivity;
import me.yokeyword.fragmentation_swipeback.SwipeBackActivity;
import rx.Observable;

/**
 * chaos框架基类
 */
public abstract class BaseAct extends SwipeBackActivity implements UiCallback {

    UiDelegate uiDelegate;
    protected long windowDuration=2;//默认防抖动两秒
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getUiDelegate().onCreate();

        if (isRegisterEvent()){
            BusFactory.getBus().register(this);
        }
    }
    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        bindEvent();
        initData();
        setListener();
    }
    protected UiDelegate getUiDelegate() {
        if (uiDelegate == null) {
            uiDelegate = UiDelegateBase.create(this);
        }
        return uiDelegate;
    }
    protected boolean isRegisterEvent() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getUiDelegate().destory();
    }

    /**
     * 防抖动监听
     * @param view
     * @return
     */
    public Observable onClickFirst(View view){
        return throttleFirst(RxView.clicks(view));//两秒钟之内只取一个点击事件，防抖操作
    }
    /**
     * 防抖动，防止快速点击
     *
     * @param observable
     * @param <T>
     * @return
     */
    protected <T extends Object> Observable<T> throttleFirst(Observable<T> observable) {
        return observable.throttleFirst(windowDuration, TimeUnit.MILLISECONDS);
    }

    /**
     * 将事件与生命周期绑定
     *
     * @param observable
     * @return
     */
    protected <T extends Object> Observable<T> bindLife(Observable<T> observable) {
        return (Observable<T>) observable.compose(bindToLifecycle());
    }

    /**
     * 指定事件在哪个生命周期结束
     *
     * @param observable
     * @param event      生命周期
     * @return
     */
    protected <T extends Object> Observable<T> bindUntil(Observable<T> observable, ActivityEvent event) {
        return (Observable<T>) observable.compose(bindUntilEvent(event));
    }
}
